package func.study.groovy.shell1

import func.study.groovy.shell.DocumentBinding

/**
 * shell脚本解析
 * Created by yao_pc on 2017/8/6.
 */
class ShellParser {

    private Script script

    ShellParser(String scriptText, DocumentBinding customBinding, String dslKey) {
        this.script = createScript(scriptText, customBinding, dslKey)
    }


    def run() {
        this.script.run()
    }

    def createScript(scriptText, customBinding, dslKey) {
        def shell = new GroovyShell(customBinding)
        def script = shell.parse(scriptText)
        injectMethod(script, dslKey)
        return script
    }

    def injectMethod(script, dslKey) {
        //存放结果
        script.getMetaClass().setProperty('map', new HashMap())
        script.getMetaClass().setProperty('urls', new ArrayList())
        //总入口,返回结果
        script.getMetaClass().graber = {dslMap ->
            //获取要执行的闭包,并执行
            dslMap.get(dslKey)()
            [map, urls]
        }
        //选择器方法
        script.getMetaClass().$ = {cssSeletor ->
            doc.select(cssSeletor)
        }
        //设置属性
        script.getMetaClass().set = {name, closure ->
            values = closure()
            name = name.trim()
            if(name.contains("_")) {
                String[] keys = name.split("_")
                for(i=0; i<keys.length; i++) {
                    map.put(keys[i], values[i])
                }
            } else {
                map.put(name, values)
            }
        }
        script.getMetaClass().urls = {closure ->
            def result = closure()
            if(result instanceof String) {
                urls.add(result)
            } else if(result instanceof List) {
                urls = result
            }
        }

        script.getMetaClass().result = {closure ->
            m = new HashMap()
            closure.getMetaClass().leftShift = { other ->
                println "other"
                println other
                m.put(real, other)
            }
            closure()
            println "m"
            println m
        }




    }
}
